package personal.xjl._23java1studentdemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import personal.xjl._23java1studentdemo.mapper.CourseMapper;
import personal.xjl._23java1studentdemo.model.Course;
import personal.xjl._23java1studentdemo.model.Student;
import personal.xjl._23java1studentdemo.service.CourseService;

import java.util.List;

@Controller
@RequestMapping("/Course")
public class CourseController {
    @Autowired
    CourseService courseService;
    @Autowired
    CourseMapper courseMapper;

    @RequestMapping("list")
    public String list(Model model) {
        List<Course> courses = courseService.findAll();
        model.addAttribute("courses", courses);
        return "listCourses";
    }

    @RequestMapping("remove")
    public String remove(int id) {
        courseService.remove(id);
        return "redirect:/Course/list/1/3";
    }

    @RequestMapping("add")
    public String add(Course course) {
        courseService.add(course);
        return "redirect:/Course/list/1/3";
    }

    @RequestMapping("toEdit")
    public String toEdit(int id, Model model) {
        Course oldCourse = courseService.findById(id);
        model.addAttribute("course", oldCourse);
        return "editCourse";
    }

    @RequestMapping("edit")
    public String edit(Course course) {
        courseService.edit(course);
        return "redirect:/Course/list/1/3";
    }

    @RequestMapping("list/{currPage}/{pageSize}")
    // 分页显示
    public String list(Model model, @PathVariable("currPage") int currPage, @PathVariable("pageSize") int pageSize) {
        if (currPage < 1) currPage = 1;
        if (pageSize <= 0) pageSize = 5;
        List<Course> courses = courseService.findByPage(currPage, pageSize);
        model.addAttribute("courses", courses);
        return "listCourses";
    }

    @GetMapping("/Course/list")
    public String listCourses(Model model) {
        List<Course> courses = courseMapper.selectAll();
        if (courses == null || courses.isEmpty()) {
            // 可以添加提示信息到模型中
            model.addAttribute("message", "暂无课程信息");
        } else {
            model.addAttribute("courses", courses);
        }
        return "listCourses";
    }
}
